package com.sky.com.sky.web.app;

import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 设置默认收货地址
     * @param addressBook
     * @return
     * **/
   @PutMapping("/default")
   public Result setDefault(@RequestBody AddressBook addressBook){
        addressBookService.setDefaultAddress(addressBook);
        return Result.success();
   }



    /**
     * 查询登陆人收货地址列表
     * @return
     * **/
    @GetMapping("/list")
    public Result getList(){
        //调用业务
        List<AddressBook> addressBookList= addressBookService.getList();
        //响应结果
        return Result.success(addressBookList);
    }



    /**
     * 新增收货地址
     * @param addressBook
     * @return
     * **/
    @PostMapping
    public Result add(@RequestBody AddressBook addressBook){
      //调用业务
        addressBookService.save(addressBook);
        //响应结果
        return Result.success();

    }


    /**
     * 查询默认收货地址
     * @return
     * **/
    @GetMapping("/default")
    public Result getDefaultAddress(){
        AddressBook defaultaddressBook = addressBookService.getDefaultAddress();
        if(defaultaddressBook != null){
            return Result.success(defaultaddressBook);
        }
        return Result.error("当前没有默认收货地址，请添加");
    }


    /**
     * 根据ID查询收货地址
     * @param id
     * @return
     * **/
   @GetMapping("/{id}")
   public Result<AddressBook> getById(@PathVariable("id") Long id){
       AddressBook addressBook = addressBookService.getById(id);
       return Result.success(addressBook);
   }


    /**
     * 修改收货地址
     * @param addressBook
     * @return
     * **/
    @PutMapping
    public Result updateById(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return Result.success();
    }



    // 根据id删除地址
    @DeleteMapping
    public Result deleteById(Long id){
        addressBookService.deleteById(id);
        return Result.success();
    }



}
